const { BaseCommand } = require("./base");

/**
 * 把数组(content)中的元素使用指定符号(delimiter)分割，组合得到指定属性名(props)的对象数组(ret)
 * @example
 * content = ["Key1,Key2,Key3", "Value1,Value2,Value3"];
 * delimiter = ",";
 * props = "k,v"
 * // 得到结果
 * ret = [
 *   {k: "Key1", v: "Value1"},
 *   {k: "Key2", v: "Value2"},
 *   {k: "Key3", v: "Value3"},
 * ]
 */
class AssembleCommand extends BaseCommand {
    async execute() {
        let delimiter = this.selfData.delimiter;
        if (delimiter) {
            delimiter = new RegExp(delimiter);
        }
        let props = this.selfData.props;
        if (delimiter && typeof props === "string") {
            props = props.split(delimiter);
        }
        const arrays = this.content.map((v) =>
            delimiter && typeof v === "string" ? v.split(delimiter) : v,
        );
        const num_item = arrays.reduce((prev, curr) => {
            return Math.max(prev, curr.length);
        }, 0);
        const ret = [];
        for (let idx_item = 0; idx_item < num_item; ++idx_item) {
            const tmp = {};
            props.forEach((v, prop_idx) => {
                tmp[v] = arrays[prop_idx][idx_item];
            });
            ret.push(tmp);
        }
        return ret;
    }

    getRequiredParams() {
        return ["props"];
    }

    getRequireContent() {
        return true;
    }
}

module.exports = {
    AssembleCommand,
};
